import {
  app,
  BrowserWindow,
  ipcMain
} from 'electron'

import {
  autoUpdater
} from 'electron-updater'
/**
 * Set `__static` path to static files in production
 * https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-static-assets.html
 */
if (process.env.NODE_ENV !== 'development') {
  global.__static = require('path').join(__dirname, '/static').replace(/\\/g, '\\\\')
}

let mainWindow
let webContents
let checkWindow
const winURL = process.env.NODE_ENV === 'development' ?
  `http://localhost:9080` :
  `file://${__dirname}/index.html`

function createWindow() {
  console.log('createWindow');
  /**
   * Initial window options
   */
  mainWindow = new BrowserWindow({
    height: 720,
    useContentSize: false,
    width: 1280,
    show: false,
    title: '123'
  })
  mainWindow.setResizable(false);
  mainWindow.setMenu(null);
  mainWindow.setMaximizable(false);
  mainWindow.loadURL(winURL)
  mainWindow.on('closed', () => {
    mainWindow = null
  })

  mainWindow.webContents.on('did-finish-load', function () {
    mainWindow.show();
    if (process.env.NODE_ENV === 'production')
      autoUpdater.checkForUpdates()
  });

}

//app.on('ready', createWindow)

var check_update = true;
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('browser-window-focus', () => {
  if (mainWindow === null) {
    createWindow()
  }
  if (process.env.NODE_ENV === 'production' && check_update)
    autoUpdater.checkForUpdates()
})

/**  
 * Auto Updater
 *
 * Uncomment the following code below and install `electron-updater` to
 * support auto updating. Code Signing with a valid certificate is required.
 * https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-electron-builder.html#auto-updating
 */


app.on('ready', () => {
  createWindow()
})


autoUpdater.on('update-downloaded', () => {
  sendUpdateMessage("downloaded");
})

autoUpdater.on('update-available', function (message) {
  sendUpdateMessage('newversion', message)
});

autoUpdater.on('error', function (message) {
  check_update = false;
  sendUpdateMessage('error', message)
});

// 更新下载进度事件
autoUpdater.on('download-progress', function (progressObj) {
  sendUpdateMessage('downloadProgress', progressObj)
})

autoUpdater.setFeedURL("http://update.oniongame.cn:5180/electron/")

// 主进程主动发送消息给渲染进程函数
function sendUpdateMessage(message, data) {
  console.log({
    message,
    data
  });
  mainWindow.webContents.send('message', {
    message,
    data
  });
}

ipcMain.on('updateNow', (e, arg) => {
  autoUpdater.quitAndInstall();
});